package top.infopub.mgr.adm.web;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.adm.domain.MeetingRecordAssist;
import top.infopub.mgr.adm.domain.MeetingRecordDomain;
import top.infopub.mgr.adm.service.MeetingRecordService;
import top.infopub.mgr.adm.service.MeetingRoomService;
import top.infopub.mgr.adm.service.ServeRecordService;
import top.infopub.mgr.adm.vo.MeetingRecordVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.adm.MeetingRecord;
import top.infopub.model.adm.MeetingRecordAtt;
import top.infopub.model.adm.MeetingRoom;
import top.infopub.model.adm.ServeRecord;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 会议申请/会议室管理
 * @author Awoke
 * @version 2020年3月20日
 * @see MeetingRecordController
 * @since
 */
@Controller
@RequestMapping("/meetingRecord")
public class MeetingRecordController extends GenericFlowController {

    @Autowired
    private MeetingRecordService meetingRecordService;

    @Autowired
    private MeetingRoomService meetingRoomService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ServeRecordService serveRecordService;

    /**
     * 会议申请列表页面
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "adm/lay-meetingRecord-list";
    }

    /**
     * 会议申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<MeetingRecordDomain> queryDataByCondition(MeetingRecordVo meetingRecordVo,
                                                           ParamPage paramPage) {
        Page<MeetingRecordDomain> page = new Page<MeetingRecordDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，会议日期增加一天
        if (meetingRecordVo.getMeetingEndTime() != null) {
            meetingRecordVo.setMeetingEndTime(DateUtils.addDays(
                meetingRecordVo.getMeetingEndTime(), 1));
        }
        page = meetingRecordService.selectByDomainWhere(page, meetingRecordVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 会议申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<MeetingRecordDomain> queryMyCheckDataByCondition(MeetingRecordVo meetingRecordVo,
                                                                  ParamPage paramPage) {
        Page<MeetingRecordDomain> page = new Page<MeetingRecordDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，会议日期增加一天
        if (meetingRecordVo.getMeetingEndTime() != null) {
            meetingRecordVo.setMeetingEndTime(DateUtils.addDays(
                meetingRecordVo.getMeetingEndTime(), 1));
        }
        meetingRecordVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = meetingRecordService.selectMyCheckByDomainWhere(page, meetingRecordVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 跳转到会议室申请新增页面
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //带入所有会议室
        MeetingRoom meetingRoom = new MeetingRoom();
        meetingRoom.setState(1);
        List<MeetingRoom> meetingRooms = meetingRoomService.selectByEntityWhere(meetingRoom);
        request.setAttribute("meetingRoomList", meetingRooms);
        return "adm/lay-meetingRecord-add";
    }

    /**
     * 跳转到会议室管理页面
     * @return
     */
    @RequestMapping("/mgr")
    public String toMgr(HttpServletRequest request) {
        return "adm/lay-meeting-add";
    }

    /**
     * 会议申请-新增管理会议室
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/manage")
    @ResponseBody
    public RspVo manage(MeetingRecordAssist meetingRecordAssist)
        throws ParseException {

        String[] roomNames = meetingRecordAssist.getRoomNames();
        if (roomNames != null && roomNames.length > 0) {
            for (int i = 0; i < roomNames.length; i++ ) {
                String roomName = roomNames[i];
                String holdNum = meetingRecordAssist.getHoldNums()[i];
                Integer holdNumber = Integer.parseInt(holdNum);
                if (StringUtils.isNotEmpty(roomName)) {
                    if (StringUtils.isEmpty(holdNum)) {
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("会议室容纳人数未填");
                    }
                    if (holdNumber == 0) {
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("会议室容纳人数为0");
                    }
                    int count = meetingRoomService.queryMeetingRoomByName(roomName);
                    if (count != 0) {
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("会议室名称重复");
                    }
                }
                else if (StringUtils.isNotEmpty(holdNum)) {
                    if (StringUtils.isEmpty(roomName)) {
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("会议室名称未填");
                    }
                }
            }
        }
        else {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("会议室名称未填");
        }
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        if (roomNames != null && roomNames.length > 0) {
            for (int i = 0; i < roomNames.length; i++ ) {
                String roomCode = codeGeneratorConfigService.generatorCode("adm_meeting_room");
                String roomName = roomNames[i];
                String holdNum = meetingRecordAssist.getHoldNums()[i];
                Integer holdNumber = Integer.parseInt(holdNum);
                if (StringUtils.isEmpty(roomName) && StringUtils.isEmpty(holdNum)
                    && holdNumber == 0) {
                    continue;
                }
                MeetingRoom meetingRoom = new MeetingRoom();
                String meetingRoomId = IdFactory.getUUIDUpper();//自动生成主键
                meetingRoom.setId(meetingRoomId);
                meetingRoom.setRoomCode(roomCode);
                meetingRoom.setRoomName(roomName);
                meetingRoom.setHoldNum(holdNumber);
                meetingRoom.setState(1);
                meetingRoom.setAddBy(vo.getId());
                meetingRoom.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                meetingRoom.setUptBy(vo.getId());
                meetingRoom.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                meetingRoomService.insert(meetingRoom);
            }
        }
        return RspVo.getSuccessResponse();
    }

    /**
     * 接待申请-新增
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(MeetingRecordAssist meetingRecordAssist)
        throws ParseException {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String meetingDates = meetingRecordAssist.getMeetingDates();
        String meetingStartTimes = meetingRecordAssist.getMeetingStartTimes();
        String meetingEndTimes = meetingRecordAssist.getMeetingEndTimes();
        String meetingStartTime = meetingDates + " " + meetingStartTimes;
        String meetingEndTime = meetingDates + " " + meetingEndTimes;
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date meetingDate = df1.parse(meetingDates);
        Date meetingStartTimeDate = df.parse(meetingStartTime);
        Date meetingEndTimeDate = df.parse(meetingEndTime);

        meetingRecordAssist.setMeetingDate(meetingDate);
        meetingRecordAssist.setMeetingStartTime(meetingStartTimeDate);
        meetingRecordAssist.setMeetingEndTime(meetingEndTimeDate);

        if (StringUtils.isBlank(meetingRecordAssist.getId())) {
            SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");
            List<MeetingRecord> meetingRecordList = meetingRecordService.isExistTime(meetingRecordAssist);
            //判断会议时间是否有重叠
            if (meetingRecordList != null && meetingRecordList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (MeetingRecord meetingRecord : meetingRecordList) {
                    //数据库中的开始时间
                    long meetingStartTimeLong = meetingRecord.getMeetingStartTime().getTime();
                    //数据库中的结束时间
                    long meetingEndTimeLong = meetingRecord.getMeetingEndTime().getTime();
                    //前端传的开始时间
                    long meetingStartTimeAssist = meetingRecordAssist.getMeetingStartTime().getTime();
                    //前端传的结束时间
                    long meetingEndTimeAssist = meetingRecordAssist.getMeetingEndTime().getTime();
                    if (meetingStartTimeAssist >= meetingStartTimeLong
                        && meetingEndTimeAssist <= meetingEndTimeLong) {
                        stringBuilder.append(df2.format(meetingRecordAssist.getMeetingStartTime()) + "-"
                                             + df2.format(meetingRecordAssist.getMeetingEndTime()) + ",");
                    }
                    else if (meetingStartTimeAssist <= meetingStartTimeLong
                             && meetingEndTimeAssist >= meetingEndTimeLong) {
                        stringBuilder.append(df2.format(meetingRecord.getMeetingStartTime()) + "-"
                                             + df2.format(meetingRecord.getMeetingEndTime()) + ",");
                    }
                    else if (meetingStartTimeAssist <= meetingStartTimeLong
                             && meetingEndTimeAssist <= meetingEndTimeLong
                             && meetingEndTimeAssist >= meetingStartTimeLong) {
                        stringBuilder.append(df2.format(meetingRecord.getMeetingStartTime()) + "-"
                                             + df2.format(meetingRecordAssist.getMeetingEndTime()) + ",");
                    }
                    else if (meetingStartTimeAssist >= meetingStartTimeLong
                             && meetingEndTimeAssist >= meetingEndTimeLong
                             && meetingStartTimeAssist <= meetingEndTimeLong
                             && meetingEndTimeAssist >= meetingStartTimeLong) {
                        stringBuilder.append(df2.format(meetingRecordAssist.getMeetingStartTime()) + "-"
                                             + df2.format(meetingRecord.getMeetingEndTime()) + ",");
                    }

                }
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("会议申请-会议时间存在重叠~【重叠时间段为"
                                                                + stringBuilder.substring(0,
                                                                    stringBuilder.length() - 1));
            }
        }

        if (StringUtils.isBlank(meetingRecordAssist.getId())) {
            SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");
            ServeRecord serveRecord = new ServeRecord();
            serveRecord.setMeetingStartTime(meetingStartTimeDate);
            serveRecord.setMeetingEndTime(meetingEndTimeDate);
            serveRecord.setMeetingRoomId(meetingRecordAssist.getMeetingRoomId());
            List<ServeRecord> serveRecordList = serveRecordService.isExistTime(serveRecord);
            //判断会议时间是否有重叠
            if (serveRecordList != null && serveRecordList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (ServeRecord sRecord : serveRecordList) {
                    //数据库中的开始时间
                    long meetingStartTimeLong = sRecord.getMeetingStartTime().getTime();
                    //数据库中的结束时间
                    long meetingEndTimeLong = sRecord.getMeetingEndTime().getTime();
                    //前端传的开始时间
                    long meetingStartTimeAssist = meetingRecordAssist.getMeetingStartTime().getTime();
                    //前端传的结束时间
                    long meetingEndTimeAssist = meetingRecordAssist.getMeetingEndTime().getTime();
                    if (meetingStartTimeAssist >= meetingStartTimeLong
                        && meetingEndTimeAssist <= meetingEndTimeLong) {
                        stringBuilder.append(df2.format(meetingRecordAssist.getMeetingStartTime()) + "-"
                                             + df2.format(meetingRecordAssist.getMeetingEndTime()) + ",");
                    }
                    else if (meetingStartTimeAssist <= meetingStartTimeLong
                             && meetingEndTimeAssist >= meetingEndTimeLong) {
                        stringBuilder.append(df2.format(sRecord.getMeetingStartTime()) + "-"
                                             + df2.format(sRecord.getMeetingEndTime()) + ",");
                    }
                    else if (meetingStartTimeAssist <= meetingStartTimeLong
                             && meetingEndTimeAssist <= meetingEndTimeLong
                             && meetingEndTimeAssist >= meetingStartTimeLong) {
                        stringBuilder.append(df2.format(sRecord.getMeetingStartTime()) + "-"
                                             + df2.format(meetingRecordAssist.getMeetingEndTime()) + ",");
                    }
                    else if (meetingStartTimeAssist >= meetingStartTimeLong
                             && meetingEndTimeAssist >= meetingEndTimeLong
                             && meetingStartTimeAssist <= meetingEndTimeLong
                             && meetingEndTimeAssist >= meetingStartTimeLong) {
                        stringBuilder.append(df2.format(meetingRecordAssist.getMeetingStartTime()) + "-"
                                             + df2.format(sRecord.getMeetingEndTime()) + ",");
                    }
                }
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("接待申请-会议时间存在重叠~【重叠时间段为"
                                                                + stringBuilder.substring(0,
                                                                    stringBuilder.length() - 1));
            }
        }

        //会议申请表处理
        meetingRecordAssist.setHrDeptId(meetingRecordAssist.getHrDeptid());
        meetingRecordAssist.setHrOrgId(meetingRecordAssist.getHrOrgid());
        meetingRecordAssist.setStaffName(meetingRecordAssist.getStaffname());
        meetingRecordAssist.setHrStaffApplyId(meetingRecordAssist.getHrStaffApplyid());
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        meetingRecordAssist.setId(id);
        meetingRecordAssist.setAddBy(vo.getId());
        meetingRecordAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("adm_meeting_record");
        meetingRecordAssist.setCodes(code);
        // 处理processId
        meetingRecordAssist.setProcessId(IdFactory.getUUIDUpper());
        meetingRecordAssist.setProcessStatus("1");//审批中
        meetingRecordAssist.setUptBy(vo.getId());
        meetingRecordAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<MeetingRecordAtt> meetingRecordAtts = new ArrayList<MeetingRecordAtt>();
        //附件资料(选填)
        String[] fileAtts1 = meetingRecordAssist.getFileAtts1();
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                MeetingRecordAtt meetingRecordAtt = createFileAtt(vo, id, file);
                meetingRecordAtt.setTypes("1");
                meetingRecordAtts.add(meetingRecordAtt);
            }
        }

        meetingRecordService.saveMeetingRecord(meetingRecordAssist, meetingRecordAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, null, null);
        return RspVo.getSuccessResponse();
    }

    private MeetingRecordAtt createFileAtt(AuthorizationVO vo, String recordId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        MeetingRecordAtt fileAtt = new MeetingRecordAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setRecordId(recordId);//接待申请id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "meetingRecord";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传会议申请附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询会议申请详细  > 注意：方法命名必须为：toDealOrDetail
     * @param id 会议申请id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        MeetingRecordVo meetingRecordVo = meetingRecordService.queryById(id);
        request.setAttribute("modelDetail", meetingRecordVo);
        map.put("meetingRecordVo", meetingRecordVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, meetingRecordVo.getProcessId());
        return new ModelAndView("adm/lay-meetingRecord-detail", map);
    }
}
